package com.iwomy.secureplat.platform.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.iwomy.secureplat.admin.api.feign.RemoteUserService;
import com.iwomy.secureplat.common.core.util.R;
import com.iwomy.secureplat.common.data.datascope.DataScope;
import com.iwomy.secureplat.common.security.util.SecurityUtils;
import com.iwomy.secureplat.platform.dto.BasicDeviceModelDTO;
import com.iwomy.secureplat.platform.entity.*;
import com.iwomy.secureplat.platform.mapper.BasicCommunicationModelMapper;
import com.iwomy.secureplat.platform.mapper.BasicOperatorTypeMapper;
import com.iwomy.secureplat.platform.utils.DeptFillUtils;
import com.iwomy.secureplat.platform.utils.RemoteDeptUtils;
import com.iwomy.secureplat.platform.mapper.BasicAuthorizationRecordMapper;
import com.iwomy.secureplat.platform.mapper.BasicDeviceModelMapper;
import com.iwomy.secureplat.platform.service.BasicDeviceModelService;
import com.iwomy.secureplat.platform.vo.BasicDeviceModelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备型号表
 *
 * @author pig
 * @date 2023-11-14 14:43:58
 */
@Service
public class BasicDeviceModelServiceImpl extends ServiceImpl<BasicDeviceModelMapper, BasicDeviceModelEntity> implements BasicDeviceModelService {

	@Autowired
	private RemoteDeptUtils remoteDeptUtils;

	@Autowired
	private RemoteUserService remoteUserService;

	@Autowired
	private BasicAuthorizationRecordMapper authorizationRecord;

	@Autowired
	private BasicCommunicationModelMapper basicCommunicationModelMapper;

	@Autowired
	private BasicOperatorTypeMapper basicOperatorTypeMapper;

	@Override
	public Page<BasicDeviceModelVO> getBasicDeviceModelPage(Page page, BasicDeviceModelDTO basicDeviceModelDTO) {
		LambdaQueryWrapper<BasicDeviceModelEntity> queryWrapper = Wrappers.lambdaQuery();
		List<BasicDeviceModelEntity> list = this.baseMapper.selectListByScope(queryWrapper, new DataScope());
		List<Long> deviceModelId = list.stream().map(BasicDeviceModelEntity::getId).collect(Collectors.toList());

		if (ObjectUtil.isEmpty(deviceModelId)) return page;

		//多表查询
		MPJLambdaWrapper<BasicDeviceModelEntity> wrapper = new MPJLambdaWrapper<>();
		wrapper.selectAll(BasicDeviceModelEntity.class)
				.selectAs(BasicDeviceTypeEntity::getTypeName, BasicDeviceModelVO::getDeviceType)

				.leftJoin(BasicDeviceTypeEntity.class, BasicDeviceTypeEntity::getId, BasicDeviceModelEntity::getDeviceTypeId);

		if (ObjectUtil.isNotEmpty(basicDeviceModelDTO.getDeviceTypeId())) {
			wrapper.eq(BasicDeviceModelEntity::getDeviceTypeId, basicDeviceModelDTO.getDeviceTypeId());
		}
		if (StrUtil.isNotEmpty(basicDeviceModelDTO.getDeviceModelName())) {
			wrapper.like(BasicDeviceModelEntity::getDeviceModelName, basicDeviceModelDTO.getDeviceModelName());
		}
		if (ArrayUtil.isNotEmpty(basicDeviceModelDTO.getCreateTime())) {
			wrapper.ge(BasicDeviceModelEntity::getCreateTime, basicDeviceModelDTO.getCreateTime()[0]).le(BasicDeviceModelEntity::getCreateTime,
					basicDeviceModelDTO.getCreateTime()[1]);
		}
		if (ObjectUtil.isNotEmpty(basicDeviceModelDTO.getCommunicationModelId())) {
			wrapper.eq(BasicDeviceModelEntity::getCommunicationModelId, basicDeviceModelDTO.getCommunicationModelId());
		}
		if (ObjectUtil.isNotEmpty(basicDeviceModelDTO.getOperatorId())) {
			wrapper.eq(BasicDeviceModelEntity::getOperatorId, basicDeviceModelDTO.getOperatorId());
		}
		if (StrUtil.isNotEmpty(basicDeviceModelDTO.getProducer())) {
			wrapper.like(BasicDeviceModelEntity::getProducer, basicDeviceModelDTO.getProducer());
		}

		wrapper.in(BasicDeviceModelEntity::getId, deviceModelId);

		Page<BasicDeviceModelVO> basicDeviceModelPage = this.getBaseMapper().selectJoinPage(page, BasicDeviceModelVO.class, wrapper);
		DeptFillUtils.fill(basicDeviceModelPage);
		List<BasicDeviceModelVO> records = basicDeviceModelPage.getRecords();
		records.forEach(this::enrichDeviceModelVO);
		return basicDeviceModelPage;
	}

	@Override
	public BasicDeviceModelVO getDeviceModelById(Long id) {
		//多表查询
		MPJLambdaWrapper<BasicDeviceModelEntity> wrapper = new MPJLambdaWrapper<>();
		wrapper.selectAll(BasicDeviceModelEntity.class)
				.selectAs(BasicDeviceTypeEntity::getTypeName, BasicDeviceModelVO::getDeviceType)

				.leftJoin(BasicDeviceTypeEntity.class, BasicDeviceTypeEntity::getId, BasicDeviceModelEntity::getDeviceTypeId)
				.eq(BasicDeviceModelEntity::getId, id);

		BasicDeviceModelVO basicDeviceModel = this.getBaseMapper().selectJoinOne(BasicDeviceModelVO.class, wrapper);
		enrichDeviceModelVO(basicDeviceModel);
		return basicDeviceModel;
	}


	/**
	 * 查询授权管理员的部门
	 */
	@Override
	public R authorize(BasicDeviceModelDTO basicDeviceModelDTO) {
		String deptIdStr = (String) remoteUserService.getUserByPhone(basicDeviceModelDTO.getPhone()).getData();
		if (deptIdStr != null) {
			Long deptId = Long.parseLong(deptIdStr);
			if (remoteDeptUtils.getAuthorizeById(deptId).getData() != null) {
				return R.ok(remoteDeptUtils.getAuthorizeById(deptId).getData());
			} else {
				return R.failed("该公司不在可平行过户范围内");
			}

		}
		return R.failed("未找到对应用户");
	}

	//产品库列表
	@Override
	public Page<BasicDeviceModelVO> getBasicDeviceStockPage(Page page, BasicDeviceModelDTO basicDeviceModelDTO) {
		Map<String, Object> data = remoteDeptUtils.getDept(SecurityUtils.getUser().getDeptId());
		String parentIdString = (String) data.getOrDefault("parentId", null);
		Long parentId = Long.parseLong(parentIdString);
		List<BasicAuthorizationRecordEntity> list = new ArrayList<>();
		List<Long> deviceModelId = new ArrayList<>();
		if (parentId != 0) {
			LambdaQueryWrapper<BasicAuthorizationRecordEntity> queryWrapper = Wrappers.lambdaQuery();
			queryWrapper.eq(BasicAuthorizationRecordEntity::getState, 10);
			queryWrapper.in(BasicAuthorizationRecordEntity::getDeptId, SecurityUtils.getUser().getDeptId());
			list = authorizationRecord.selectList(queryWrapper);
			deviceModelId = list.stream().map(BasicAuthorizationRecordEntity::getDeviceModelId).collect(Collectors.toList());
			if (ObjectUtil.isEmpty(deviceModelId)) return page;
		}

		//多表查询
		MPJLambdaWrapper<BasicDeviceModelEntity> wrapper = new MPJLambdaWrapper<>();
		wrapper.selectAll(BasicDeviceModelEntity.class)
				.selectAs(BasicDeviceTypeEntity::getTypeName, BasicDeviceModelVO::getDeviceType)

				.leftJoin(BasicDeviceTypeEntity.class, BasicDeviceTypeEntity::getId, BasicDeviceModelEntity::getDeviceTypeId)
				.eq(BasicDeviceModelEntity::getState, 10);

		if (deviceModelId != null && !deviceModelId.isEmpty()) {
			wrapper.in(BasicDeviceModelEntity::getId, deviceModelId);
		}

		if (ObjectUtil.isNotEmpty(basicDeviceModelDTO.getDeviceTypeId())) {
			wrapper.eq(BasicDeviceModelEntity::getDeviceTypeId, basicDeviceModelDTO.getDeviceTypeId());
		}
		if (StrUtil.isNotEmpty(basicDeviceModelDTO.getDeviceModelName())) {
			wrapper.like(BasicDeviceModelEntity::getDeviceModelName, basicDeviceModelDTO.getDeviceModelName());
		}
		if (ObjectUtil.isNotEmpty(basicDeviceModelDTO.getCommunicationModelId())) {
			wrapper.eq(BasicDeviceModelEntity::getCommunicationModelId, basicDeviceModelDTO.getCommunicationModelId());
		}
		if (ObjectUtil.isNotEmpty(basicDeviceModelDTO.getOperatorId())) {
			wrapper.eq(BasicDeviceModelEntity::getOperatorId, basicDeviceModelDTO.getOperatorId());
		}
		if (StrUtil.isNotEmpty(basicDeviceModelDTO.getProducer())) {
			wrapper.like(BasicDeviceModelEntity::getProducer, basicDeviceModelDTO.getProducer());
		}

		Page<BasicDeviceModelVO> basicDeviceModelPage = this.getBaseMapper().selectJoinPage(page, BasicDeviceModelVO.class, wrapper);
		List<BasicDeviceModelVO> records = basicDeviceModelPage.getRecords();

		for (BasicDeviceModelVO record : records) {
			List<BasicAuthorizationRecordEntity> matchingRecords = list.stream()
					.filter(entity -> entity.getDeviceModelId().equals(record.getId()))
					.collect(Collectors.toList());

			if (!matchingRecords.isEmpty()) {
				record.setAuthorizedDeptId(matchingRecords.get(0).getAuthorizedDeptId());
				record.setDeptName(remoteDeptUtils.getDeptName(record.getAuthorizedDeptId()));
			} else {
				// 如果没有匹配的记录，则将 authorizedDeptId 属性设置为 null 或默认值
				record.setAuthorizedDeptId(null); // 或者 record.setAuthorizedDeptId(defaultValue);
			}
		}

		records.forEach(this::enrichDeviceModelVO);
		return basicDeviceModelPage;
	}

	@Override
	public List<BasicDeviceModelVO> getDeviceModelList(BasicDeviceModelEntity basicDeviceModel) {
		Map<String, Object> data = remoteDeptUtils.getDept(SecurityUtils.getUser().getDeptId());
		String parentIdString = (String) data.getOrDefault("parentId", null);
		Long parentId = Long.parseLong(parentIdString);

		List<BasicDeviceModelVO> records = new ArrayList<>();
		//是租户时，设备型号都显示
		if (parentId == 0) {
			MPJLambdaWrapper<BasicDeviceModelEntity> wrapper = new MPJLambdaWrapper<>();
			wrapper.selectAll(BasicDeviceModelEntity.class)
					.selectAs(BasicDeviceTypeEntity::getTypeName, BasicDeviceModelVO::getDeviceType)

					.leftJoin(BasicDeviceTypeEntity.class, BasicDeviceTypeEntity::getId, BasicDeviceModelEntity::getDeviceTypeId)
					.in(ObjectUtil.isNotNull(basicDeviceModel.getDeviceTypeId()), BasicDeviceModelEntity::getDeviceTypeId, basicDeviceModel.getDeviceTypeId())
					.eq(BasicDeviceModelEntity::getState, 10);
			return this.getBaseMapper().selectJoinList(BasicDeviceModelVO.class, wrapper);
		}
		LambdaQueryWrapper<BasicAuthorizationRecordEntity> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.in(BasicAuthorizationRecordEntity::getDeptId, SecurityUtils.getUser().getDeptId());
		queryWrapper.in(BasicAuthorizationRecordEntity::getDeviceTypeId, basicDeviceModel.getDeviceTypeId());
		List<BasicAuthorizationRecordEntity> authorizationRecordList = authorizationRecord.selectList(queryWrapper);
		List<Long> deviceModelId = authorizationRecordList.stream().map(BasicAuthorizationRecordEntity::getDeviceModelId).collect(Collectors.toList());

		MPJLambdaWrapper<BasicDeviceModelEntity> wrapper = new MPJLambdaWrapper<>();
		wrapper.selectAll(BasicDeviceModelEntity.class)
				.selectAs(BasicDeviceTypeEntity::getTypeName, BasicDeviceModelVO::getDeviceType)

				.leftJoin(BasicDeviceTypeEntity.class, BasicDeviceTypeEntity::getId, BasicDeviceModelEntity::getDeviceTypeId)
				.in(BasicDeviceModelEntity::getDeviceTypeId, basicDeviceModel.getDeviceTypeId())
				.eq(BasicDeviceModelEntity::getState, 10);
		if (ObjectUtil.isEmpty(deviceModelId)) {
			return Collections.emptyList();
		}

		wrapper.in(BasicDeviceModelEntity::getId, deviceModelId);
		records = this.getBaseMapper().selectJoinList(BasicDeviceModelVO.class,wrapper);
		return records;
	}

	@Override
	public List<BasicDeviceModelEntity> getAuthorizationModelList(BasicDeviceModelEntity basicDeviceModel) {
		Map<String, Object> data = remoteDeptUtils.getDept(SecurityUtils.getUser().getDeptId());
		String parentIdString = (String) data.getOrDefault("parentId", null);
		Long parentId = Long.parseLong(parentIdString);

		List<BasicDeviceModelEntity> records = new ArrayList<>();
		//是租户时，设备型号都显示
		if (parentId == 0) {
			LambdaQueryWrapper<BasicDeviceModelEntity> wrapper = Wrappers.lambdaQuery();
			wrapper.in(BasicDeviceModelEntity::getDeptId, SecurityUtils.getUser().getDeptId());
			wrapper.eq(BasicDeviceModelEntity::getState, 10);
			records = this.getBaseMapper().selectList(wrapper);
		} else {
			LambdaQueryWrapper<BasicAuthorizationRecordEntity> queryWrapper = Wrappers.lambdaQuery();
			queryWrapper.in(BasicAuthorizationRecordEntity::getAuthorizedDeptId, SecurityUtils.getUser().getDeptId());
			List<BasicAuthorizationRecordEntity> authorizationRecordList = authorizationRecord.selectList(queryWrapper);
			List<Long> deviceModelId = authorizationRecordList.stream().map(BasicAuthorizationRecordEntity::getDeviceModelId).collect(Collectors.toList());

			LambdaQueryWrapper<BasicDeviceModelEntity> wrapper = Wrappers.lambdaQuery();

			if (deviceModelId != null) {
				wrapper.in(BasicDeviceModelEntity::getId, deviceModelId);
				wrapper.eq(BasicDeviceModelEntity::getState, 10);
			}

			records = this.getBaseMapper().selectList(wrapper);
		}
		return records;
	}

	private BasicDeviceModelVO enrichDeviceModelVO(BasicDeviceModelVO record) {
		if (record.getCommunicationModelId() != null) {
			LambdaQueryWrapper<BasicCommunicationModelEntity> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(BasicCommunicationModelEntity::getId, record.getCommunicationModelId());
			BasicCommunicationModelEntity communicationModel = basicCommunicationModelMapper.selectOne(wrapper);
			record.setCommunicationModelName(communicationModel.getName());
		}
		if (record.getOperatorId() != null) {
			LambdaQueryWrapper<BasicOperatorTypeEntity> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(BasicOperatorTypeEntity::getId, record.getOperatorId());
			BasicOperatorTypeEntity operatorType = basicOperatorTypeMapper.selectOne(wrapper);
			record.setOperatorName(operatorType.getName());
		}
		return record;
	}
}